package org.example.JVM.ByteCode.Type.CONSTANT;

import lombok.Data;
import org.example.JVM.ByteCode.Type.CpInfo;
import org.example.JVM.ByteCode.Type.U1;
import org.example.JVM.ByteCode.Type.U2;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @description:UTF-8编码字符串 tag值为1
 * @author: farprt
 * @create: 2022-11-13 14:41
 **/
public class CONSTANT_Utf8_info extends CpInfo {
    private U2 length;
    private byte[] bytes;

    public CONSTANT_Utf8_info(U1 tag) {
        super(tag);
    }

    @Override
    public void read(ByteBuffer codeBuf) throws Exception {
        //先读取长度
        length = new U2(codeBuf.get(), codeBuf.get());
        bytes = new byte[length.toInt()];
        //读取指定胀肚的字节到bytes数组
        codeBuf.get(bytes, 0, bytes.length);
    }

    @Override
    public String toString() {
        return super.toString() + ",length=" + length.toInt() + ",str=" + new String(bytes, StandardCharsets.UTF_8);
    }

    public byte[] getBytes() {
        return bytes;
    }
}